using System;
using FubuMVC.Core.Runtime;

namespace FubuMVC.Core.View.WebForms
{
    public class WebFormsViewRenderer : IWebFormsViewRenderer
    {
        private readonly IModelState _modelState;
        private readonly IWebFormsControlBuilder _webFormsBuilder;

        public WebFormsViewRenderer(IModelState modelState, IWebFormsControlBuilder webFormsBuilder)
        {
            _modelState = modelState;
            _webFormsBuilder = webFormsBuilder;
        }

        public string RenderView(string viewToRender)
        {
            return RenderView<IFubuView>(viewToRender, null);
        }

        public string RenderView<TViewtype>(string viewToRender, Action<TViewtype> viewSetupAction)
            where TViewtype : class, IFubuView
        {
            var control = _webFormsBuilder.LoadControlFromVirtualPath(viewToRender, typeof(IFubuView));

            var withModel = control as IFubuViewWithModel;

            if( withModel != null )
            {
                withModel.SetModel(_modelState);
            }

            if (control != null)
            {
                if (viewSetupAction != null)
                {
                    viewSetupAction(control as TViewtype);
                }
            }

            return _webFormsBuilder.ExecuteControl(control);
        }
    }
}
